/*
 * @Description: 搜索结果页组件 - 导航
 * @Author: Rfan
 * @Date: 2022-01-19 15:22:16
 * @LastEditTime: 2023-02-25 19:05:50
 */

import { useEffect, useMemo, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Button, Checkbox, Input, message, Modal, Select } from 'antd';
import classNames from 'classnames/bind';
import { LeftOutlined } from '@ant-design/icons';
import { useSearchResultContext } from './contexts/SearchResultContext';
import SaveCondition from './components/dialog/SaveCondition';
import SearchLimit from '../SearchLimit/SearchLimit';
import { submitEntrySearch, submitFullTextSearch } from '@/api/search';
import styles from './styles/searchResultHeader.module.scss';
import { fetchRepoList } from '@/api/archivesType';

const { Search } = Input;
const cx = classNames.bind(styles);

const SearchResultHeader = () => {
  const {
    title,
    setTitle,
    getCondition,
    getFieldConditionList,
    atConditionList,
    fieldConditionList,
    setAdditionalSearch
  } = useSearchResultContext();
  const navigate = useNavigate();
  const location = useLocation();
  const { state }: any = location;
  const { params } = state;
  const { param } = params;

  const [addPlanVisible, setAddPlanVisible] = useState(false);
  /* 检索限定的弹窗 */
  const [visible, setVisible] = useState(false);
  /* 复选框按钮选择 */
  const [checkValue, setCheckValue] = useState([]);
  /* 全文上方的Input框 */
  const [inputValue, setInputValue] = useState('');
  /* 调整限定条件结构 */
  const [searchConditions, setSearchConditions] = useState([]);

  /* dbName选择 */
  const [dbNameList, setDbNameList] = useState([]);
  const [dbName, setDbName] = useState(param.commonParams.dbName);
  console.log('param', param);
  useEffect(() => {
    setDbName(param.commonParams.dbName);

    getCondition(param.fondsConditionList);
    if (param.exactMatch && !param.originalMatch) {
      setCheckValue(['exactMatch']);
    } else if (!param.exactMatch && param.originalMatch) {
      setCheckValue(['originalMatch']);
    } else if (param.exactMatch && param.originalMatch) {
      setCheckValue(['exactMatch', 'originalMatch']);
    } else {
      setCheckValue([]);
    }
  }, []);

  useEffect(() => {
    if (param.fondsConditionList?.length) {
      setSearchConditions(
        param.fondsConditionList.map((item: any) => ({
          fondId: item.fondId,
          archiveTypeIdList: item.atConditionList.map((item: any) => item.archiveTypeId)
        }))
      );
    }
  }, [param]);

  /* 搜索点击方法 */
  const navChange = ({ fieldConditionList, atConditionList }: any) => {
    getCondition(
      atConditionList.map((item: any) => ({
        fondId: item.fondId,
        atConditionList: item.archiveTypeIdList?.map((item: any) => ({ archiveTypeId: item }))
      }))
    );
    getFieldConditionList(fieldConditionList);
  };

  const onSearch = (value: string) => {
    if (value === '') {
      message.warning('请输入关键字');
      return;
    }
    const keywords = value;
    const commonParams = { dbName };
    const query = {
      pageNo: 1,
      pageSize: 10
    };

    if (state.type === 1) {
      const exactMatch = checkValue.some((item: any) => item === 'exactMatch');
      const originalMatch = checkValue.some((item: any) => item === 'originalMatch');
      const param = {
        fondsConditionList: atConditionList,
        commonParams,
        fieldConditionList,
        keywords,
        exactMatch,
        originalMatch
      };
      submitEntrySearch({ ...query, param }).then((res: any) => {
        const { data } = res;
        setAdditionalSearch(data);
      });
    } else if (state.type === 2) {
      const param = {
        fondsConditionList: atConditionList,
        commonParams,
        fieldConditionList,
        keywords
      };
      submitFullTextSearch({ ...query, param }).then((res: any) => {
        const { data } = res;
        setAdditionalSearch(data);
      });
    }
  };

  useEffect(() => {
    setTitle(state.title);
    if (state.type === 3) {
      setInputValue(param.condition);
    }
  }, [location]);

  /* 添加弹窗 */
  const addPlan = () => {
    setAddPlanVisible(true);
  };

  const onClose = () => {
    setVisible(false);
    setAddPlanVisible(false);
  };

  const onClick = () => {
    setVisible(true);
  };

  const options = [
    { label: '精确匹配', value: 'exactMatch' },
    { label: '原文匹配', value: 'originalMatch' }
  ];
  /* 复选框按钮 */
  const onChangeCheck = (event: any) => {
    setCheckValue(event);
  };
  /* 选取dbName */
  useEffect(() => {
    fetchRepoList({ atType: 1 }).then((res: any) => {
      const { data } = res;
      setDbNameList(data);
    });
  }, []);
  const changeDbName = (eve: any) => {
    setDbName(eve);
  };
  const dbNameSelect = (
    <Select
      className="select-before"
      bordered={false}
      value={dbName}
      size="small"
      options={dbNameList}
      fieldNames={{ label: 'description', value: 'name' }}
      onChange={changeDbName}
    />
  );
  return (
    <div className={cx('search-header')}>
      <div className="search-header--left">
        <Button type="text" onClick={() => navigate(-1)}>
          <LeftOutlined />
          返回
        </Button>
      </div>
      <div className={cx('search-center')}>
        <div className="search-header--center">
          <b>{title}</b>
        </div>
        {state.type === 3 ? (
          <div className={cx('search-center-input')}>
            <Input value={inputValue} />
          </div>
        ) : state.type === 2 ? (
          <>
            <div className={cx('search-center-input')}>
              <Search
                defaultValue={state.searchStr}
                onSearch={onSearch}
                enterButton={'检索'}
                prefix={dbNameSelect}
                className={cx('search')}
              />
            </div>
            <div>
              <Button type="link" onClick={onClick}>
                检索限定
              </Button>
              <Modal
                visible={visible}
                title="检索限定"
                footer={null}
                width={900}
                onCancel={onClose}
              >
                <SearchLimit onChange={navChange} type="header" param={searchConditions} />
              </Modal>
            </div>
          </>
        ) : (
          <>
            <div className={cx('search-center-input')}>
              <Search
                defaultValue={state.searchStr}
                prefix={dbNameSelect}
                onSearch={onSearch}
                enterButton={'检索'}
                className={cx('search')}
              />
            </div>
            <div className={cx('search-check')}>
              <Checkbox.Group options={options} onChange={onChangeCheck} value={checkValue} />
            </div>
            <div>
              <Button type="link" onClick={onClick}>
                检索限定
              </Button>
              <Modal
                visible={visible}
                title="检索限定"
                footer={null}
                width={900}
                onCancel={onClose}
              >
                <SearchLimit onChange={navChange} type="header" param={searchConditions} />
              </Modal>
            </div>
          </>
        )}
      </div>
      <div>
        <Button type="link" onClick={addPlan}>
          +保存到检索方案
        </Button>
      </div>
      {useMemo(
        () => (
          <>
            <SaveCondition visible={addPlanVisible} onClose={onClose} data={state} />
          </>
        ),
        [addPlanVisible]
      )}
    </div>
  );
};

export default SearchResultHeader;
